package com.huangkailong.designpattern.proxy.staticproxy;

import com.huangkailong.designpattern.proxy.common.DatasourceSupport;
import com.huangkailong.designpattern.proxy.common.Order;
import com.huangkailong.designpattern.proxy.common.OrderService;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * OrderService 静态代理类.
 *
 * @author huangkl
 * @since 1.0.0
 */
public class OrderServiceProxy implements OrderService {
    private static final DateTimeFormatter YEAR_PATTERN = DateTimeFormatter.ofPattern("yyyy");
    private final OrderService orderService;
    private final DatasourceSupport datasourceSupport;

    public OrderServiceProxy(OrderService orderService,
                             DatasourceSupport datasourceSupport) {
        this.orderService = orderService;
        this.datasourceSupport = datasourceSupport;
    }

    @Override
    public boolean createOrder(Order order) {
        LocalDateTime createdTime = order.getCreatedTime();
        String year = createdTime.format(YEAR_PATTERN);
        String datasourceName = "t_test_" + year;
        System.out.printf("通过静态代理，动态的把数据库切换到了：%s\n", datasourceName);
        datasourceSupport.setDatasourceName(datasourceName);
        return orderService.createOrder(order);
    }
}
